package com.kk.base.service.admin;

import com.kk.base.entity.admin.UserRoleTypeEnum;
import com.kk.base.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import com.kk.base.bean.PageBean;
import com.kk.base.dao.admin.UserDao;
import com.kk.base.entity.admin.User;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户管理service
 *
 * @author Administrator
 */
@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    /**
     * 根据用户id查询
     *
     * @param id
     * @return
     */
    public User find(Long id) {
        return userDao.find(id);
    }

    /**
     * 按照用户名查找用户
     *
     * @param username
     * @return
     */
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }


    /**
     * 查询网点和运输点
     *
     * @return
     */
    public List<User> findByUserTypeNot() {
        List<User> byUserTypeNot = userDao.findByUserTypeTwo(UserRoleTypeEnum.BRANCHES, UserRoleTypeEnum.TRANSPORT);
        User loginedUser = SessionUtil.getLoginedUser();
        return byUserTypeNot.stream().filter(user -> !user.getId().equals(loginedUser.getId())).collect(Collectors.toList());
    }


    /**
     * 查询省市区下可用的网点
     *
     * @param address
     * @return
     */
    public List<User> findByUserTypeAndAddress(String address) {
        List<User> userList = userDao.findByUserTypeAndAddressAndStatus(UserRoleTypeEnum.BRANCHES, address, 1);
        return userList;
    }

    /**
     * 查询快递
     *
     * @return
     */
    public List<User> findByUserType(UserRoleTypeEnum userRoleType) {
        return userDao.findByUserType(userRoleType);
    }

    /**
     * 查询快递
     *
     * @return
     */
    public List<User> findByUserTypeAndBranchId(UserRoleTypeEnum userRoleType, Long branchId) {
        return userDao.findByUserTypeAndBranchId(userRoleType, branchId);
    }


    /**
     * 查询快递
     *
     * @return
     */
    public List<User> findByUserTypeAndBranchIdAndStatus(UserRoleTypeEnum userRoleType, Long branchId, int status) {
        return userDao.findByUserTypeAndBranchIdAndStatus(userRoleType, branchId, status);
    }


    /**
     * 用户添加/编辑操作
     *
     * @param user
     * @return
     */
    public User save(User user) {
        return userDao.save(user);
    }

    /**
     * 分页查询用户列表
     * @param user
     * @param pageBean
     * @return
     */

    /**
     * 分页查询用户列表
     *
     * @param pageBean
     * @return
     */
    public PageBean<User> findList(PageBean<User> pageBean, String username, UserRoleTypeEnum userType) {
        Specification<User> specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                User loginedUser = SessionUtil.getLoginedUser();
                Predicate predicate = criteriaBuilder.equal(root.get("userType"), userType.getCode());
                predicates.add(predicate);
                if (username != null) {
                    Predicate predicate1 = criteriaBuilder.like(root.get("username"), "%" + username + "%");
                    predicates.add(predicate1);
                }
                if (loginedUser.getUserType().getCode().equals(1)) {
                    Predicate predicate2 = criteriaBuilder.equal(root.get("branchId"), loginedUser.getId());
                    predicates.add(predicate2);
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        Pageable pageable = PageRequest.of(pageBean.getCurrentPage() - 1, pageBean.getPageSize());
        Page<User> findAll = userDao.findAll(specification, pageable);
        pageBean.setContent(findAll.getContent());
        pageBean.setTotal(findAll.getTotalElements());
        pageBean.setTotalPage(findAll.getTotalPages());
        return pageBean;
    }

    /**
     * 判断用户名是否存在，添加和编辑均可判断
     *
     * @param username
     * @param id
     * @return
     */
    public boolean isExistUsername(String username, Long id) {
        User user = userDao.findByUsername(username);
        if (user != null) {
            //表示用户名存在，接下来判断是否是编辑用户的本身
            if (user.getId().longValue() != id.longValue()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 按照用户id删除
     *
     * @param id
     */
    public void delete(Long id) {
        userDao.deleteById(id);
    }

    /**
     * 返回用户总数
     *
     * @return
     */
    public long total() {
        return userDao.count();
    }


    /**
     * 查询网点下拥有的快递员
     */
    public List<User> inquiryOutletsUnderTheCourier() {
        List<User> branchesUsers = userDao.findByUserTypeAndStatus(UserRoleTypeEnum.BRANCHES, User.ADMIN_USER_STATUS_ENABLE);
        branchesUsers.forEach(item -> {
            Long aLong = userDao.countByUserTypeAndBranchId(UserRoleTypeEnum.COURIER, item.getId());
            item.setCountCourier(aLong);
        });

        return branchesUsers;
    }
}
